﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TCommon.Enum;
using ManageLiteAV;
using Newtonsoft.Json.Linq;
using System.Threading;

namespace TRTCMain.Controls
{
    public partial class UserList : UserControl
    {
        public static Dictionary<string, UserItem> itemDic = new Dictionary<string, UserItem>();
        private string hostUser = "";
        private string currentUser = "";
        private string focuserUser = "";
        private ITRTCCloud mTRTCCloud;
        public static bool isHost = false;
        public static bool ishost = false;
        private Panel userPanel = null;
        public delegate void ViewUserVideoHandler(string userName);
        public event ViewUserVideoHandler ViewUserVideoClicked;

        public delegate void HandChangedHandler(bool hasHand);
        public event HandChangedHandler HandChanged;

        public delegate void HandCountChangedHandler(int count);
        public event HandCountChangedHandler HandCountChanged;

        public delegate void FocuseUserHandler(string userName);
        public event FocuseUserHandler FocuseUserClicked;

        public delegate void UserCountChangedHandler(int count);
        public event UserCountChangedHandler UserCountChanged;

        public delegate void RemoveUserHanlder(string userid);
        public event RemoveUserHanlder RemoveUserClicked;
        public UserList()
        {
            InitializeComponent();
            userPanel = this.userListControl.GetUserPanel();
        }

        public void BeginReceiveMsg() {
            //TRTC.VideoMainForm.client.MessageReceived += receiveMsg;
        }

        public void SetHost()
        {
            isHost = true;
        }

        public void SetCloud(ITRTCCloud cloud)
        {
            mTRTCCloud = cloud;
        }

        public int Count {
            get { return itemDic.Count; }
        }

        public void AddUser(string userName)
        {

            if (!itemDic.ContainsKey(userName) && !string.IsNullOrEmpty(userName))
            {
                var item = new UserItem(userName, mTRTCCloud, isHost);
                ishost = isHost;
                item.Width = this.Width - 4;
                item.ViewUserVideoClicked += Item_ViewUserVideoClicked;
                item.FocuseUserClicked += Item_FocuseUserClicked;
                item.RemoveUserClicked += Item_RemoveUserClicked;
                var y = (item.Height + 1) * itemDic.Count;
                item.Location = new Point(2, y);

                this.userPanel.Controls.Add(item);
                itemDic.Add(userName, item);
                UserCountChanged?.Invoke(itemDic.Count);
                titleLabel.Text = $"参会者（{itemDic.Count}）";
                ReorderUser();
            }

        }

        private void Item_RemoveUserClicked(string userid)
        {
            this.RemoveUserClicked?.Invoke(userid);
        }

        public void hidepic()
        {
            foreach (Control item in this.userPanel.Controls)
            {
                foreach (Control item1 in item.Controls)
                {
                    if (item1 is PictureBox && item1.Tag != null)
                    {

                        this.Invoke(new Action(() =>
                        {
                            item1.Visible = false;
                        }));

                    }
                }
            }
        }

        public void SetUserNameColor(string userName, bool isAdd) {
            if (itemDic.ContainsKey(userName)) {
                if (isAdd)
                {
                    itemDic[userName].SetNameColor(Color.Green, true);                        
                }
                else
                {
                    itemDic[userName].SetNameColor(Color.Black, false);
                }
            }

            ReorderUser();
        }

        public List<string> GetAllUserId()
        {
            return itemDic.Keys.ToList();
        }

        private void Item_FocuseUserClicked(string userName)
        {
            focuserUser = userName;
            SetFocuseUser(userName);
            FocuseUserClicked?.Invoke(userName);
        }

        private void Item_ViewUserVideoClicked(string userName)
        {
            ViewUserVideoClicked?.Invoke(userName);
        }

        public void RemoveUer(string name)
        {
            if (itemDic.ContainsKey(name))
            {
                this.Invoke(new Action(() =>
                {
                    if (itemDic[name].IsHandOn())
                    {
                        UpdateHandStatus(name, false);
                    }

                    var control = itemDic[name];
                    this.userPanel.Controls.Remove(control);
                    itemDic.Remove(name);
                    UserCountChanged?.Invoke(itemDic.Count);
                    titleLabel.Text = $"参会者（{itemDic.Count}）";
                    ReorderUser();
                }));             
            }
        }

        private void UserList_Paint(object sender, PaintEventArgs e)
        {
            ControlPaint.DrawBorder(e.Graphics, ClientRectangle, Color.LightGray, ButtonBorderStyle.Solid);
        }
        public static string userhostname = "";
        public void SetHostUser(string userName)
        {
            //AddUser(userName);

            if (string.IsNullOrEmpty(userName))
                return;
            TCommon.AppContext.HostId = userName;
            hostUser = userName;
            string userKey = null;

            foreach (var key in itemDic.Keys)
            {
                if (key.ToUpper().StartsWith(userName.ToUpper()))
                {
                    userKey = key;
                    break;
                }
            }
            userhostname = userKey;
            if (userKey == null)
                return;
            itemDic[userKey].SetHost();
            if (currentUser == userName)
            {
                foreach (var key in itemDic.Keys)
                {
                    itemDic[key].SetIsHostUsed(true, userKey);
                    itemDic[key].SetCurrentUser(currentUser);
                }
            }
            else
            {
                foreach (var key in itemDic.Keys)
                {
                    itemDic[key].SetIsHostUsed(false, userKey);
                    itemDic[key].SetCurrentUser(currentUser);
                }
            }

            ReorderUser();
        }

        public void SetFocuseUser(string userName) {
            foreach (var key in itemDic.Keys) {
                if (key == userName)
                {
                    itemDic[key].SetFocuse(true);
                }
                else
                {
                    itemDic[key].SetFocuse(false);
                }
            }
        }

        public void SetCurrentUser(string userName)
        {
            currentUser = userName;
        }
        public void UpdateHandStatus(string userName, bool isRaised)
        {
            if (string.IsNullOrEmpty(userName))
                return;
            AddUser(userName);
            if (itemDic.ContainsKey(userName))
            {
                itemDic[userName].SetHandeRasied(isRaised);
            }

            bool isHandOn = false;
            int count = 0;
            foreach (var item in itemDic)
            {
                if (item.Value.IsHandOn())
                {
                    count++;
                }
            }
            isHandOn = count > 0;
            HandCountChanged?.Invoke(count);
            HandChanged?.Invoke(isHandOn);
        }

        public void DownAllHand() {
            foreach (var item in itemDic)
            {
                if (item.Value.IsHandOn())
                {
                    item.Value.SetHandeRasied(false);
                }
                HandCountChanged?.Invoke(0);
            }
        }

        public void UpdateUserName(string userId, string userName)
        {
            itemDic[userId].UpdateUserName(userId, userName);
        }

        public void UpdateVideoStatus(string userName, bool available)
        {
            if (string.IsNullOrEmpty(userName))
                return;
            AddUser(userName);

            if (itemDic.ContainsKey(userName))
            {
                itemDic[userName].SetVideoAvailable(available);
            }
        }

        public void UpdateAudioStatus(string userName, bool available)
        {
            if (string.IsNullOrEmpty(userName))
                return;
            AddUser(userName);

            if (itemDic.ContainsKey(userName))
            {
                itemDic[userName].SetAudioAvailable(available);
            }
        }

        public void UpdateMicroOn(string userName, bool on) {
            if (string.IsNullOrEmpty(userName))
                return;

            itemDic[userName].SetMicroOn(on);
        }

        private void ReorderUser()
        {
            var keys = itemDic.Keys.ToList();
            string host = null;
            foreach (var key in itemDic.Keys)
            {
                if (key.ToUpper().StartsWith(hostUser.ToUpper()))
                {
                    host = key;
                    break;
                }
            }
            int count = 0;
            if (!string.IsNullOrEmpty(host))
            {
                itemDic[host].Location = new Point(2, 0);
                count++;
            }
            var focuse = keys.FirstOrDefault(k => k.StartsWith(focuserUser));
            if (!string.IsNullOrEmpty(focuse) && focuse != host)
            {
                itemDic[focuse].Location = new Point(2, itemDic[focuse].Height + 1);
                count++;
            }
            var users = keys.Where(k => itemDic[k].IsOnScreen && k != focuse && k != host).ToList();

            for (int i = 0; i < users.Count; i++)
            {
                var item = itemDic[users[i]];
                item.Location = new Point(2, (item.Height + 1) * (count + i));
            }
            count = count + users.Count;

            foreach (var key in itemDic.Keys)
            {
                if (key != host && key != focuse && !users.Contains(key))
                {
                    var item = itemDic[key];
                    item.Location = new Point(2, (item.Height + 1) * (count));
                    count++;
                }
            }
        }
        public void clearNormalScreenUsers()
        {
            if (itemDic != null)
            {
                itemDic.Clear();
            }

        }

        private void UserList_SizeChanged(object sender, EventArgs e)
        {
            this.userListControl.Width = this.Width;
            this.userListControl.Height = this.Height - this.titleLabel.Height - 3;
        }
    }
}
